/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.server.bill;

import com.icee.myth.common.messageQueue.ServerMessageQueue;
import com.icee.myth.log.GameLogger;
import com.icee.myth.log.message.FileDebugGameLogMessage;
import com.icee.myth.log.message.builder.GameLogMessageBuilder;
import com.icee.myth.server.GameServer;
import com.icee.myth.server.actor.Human;
import com.icee.myth.server.message.serverMessage.builder.MapMessageBuilder;
import com.icee.myth.server.oauth.OAuthHelper;
import com.icee.myth.server.reward.CertainRewardInfo;
import com.icee.myth.utils.MD5;
import com.icee.myth.utils.StackTraceUtil;
import java.util.Properties;
import net.oauth.OAuthMessage;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/**
 *
 * @author yangyi
 */
public class Coupon implements Runnable {

    public final Human human;
    public final String passport;
    public final String code;

    public Coupon(Human human, String passport, String couponCode) {
        this.human = human;
        this.passport = passport;
        this.code = couponCode;
    }

    public void run() {
        try {
            //validate code
            if (code.length() >= 10) {
                char checkSum = code.charAt(code.length() - 1);
                String md5CheckSum = MD5.getMD5(code.substring(0, code.length() - 1).getBytes());
                if (md5CheckSum != null && md5CheckSum.toUpperCase().charAt(7) == checkSum) {
                    String content = apply();
                    CertainRewardInfo reward = null;
                    if (content == null) {
                        //重试一次
                        content = apply();
                    }
                    if (content != null) {
                        JSONObject jobj = (JSONObject) JSONValue.parse(content);
                        Long statusObj = (Long) jobj.get("status");
                        if (statusObj != null) {
                            int status = statusObj.intValue();

                            if (status == 0) {
                                JSONObject data = (JSONObject) jobj.get("data");
                                if (data != null) {
                                    reward = new CertainRewardInfo();

                                    // TODO:

//                                    JSONObject items = (JSONObject) data.get("items");
//                                    if (items != null) {
//                                        for (Map.Entry<String, JSONObject> itemEntry : (Set<Map.Entry<String, JSONObject>>) items.entrySet()) {
//                                            reward.items.put(Integer.parseInt((String) (itemEntry.getKey())), (int) (long) ((Long) (itemEntry.getValue().get("quantity"))));
//                                        }
//                                    }
                                }
                            } else {
                                GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                                    "Player[" + human.id + "] can't get coupon[" + code + "] for error code[" + status + "], ret content:" + content));
                            }
                        } else {
                            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                                    "Player[" + human.id + "] can't get coupon[" + code + "] , return content " + content));
                        }

                    } else {
                        GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                                FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                                "Player[" + human.id + "] can't get coupon[" + code + "] for invalid return value"));
                    }
                    ServerMessageQueue.queue().offer(MapMessageBuilder.buildCouponResultMessage(human.id, code, reward));
                }
            }
        } catch (Exception e) {
            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                    StackTraceUtil.getStackTrace(e)));
        }
    }

    private String apply() {
        OAuthHelper oAuthHelper = GameServer.INSTANCE.oAuthHelper;
        Properties paramProps = new Properties();
        paramProps.setProperty("oauth_token", "");
        paramProps.setProperty("coupon", code);
        paramProps.setProperty("userid", passport);
        paramProps.setProperty("areaid", "" + GameServer.INSTANCE.serverId);
        paramProps.setProperty("characterid", "" + human.id);
        paramProps.setProperty("level", "" + human.lv);
        try {
            OAuthMessage response = oAuthHelper.sendRequest(paramProps, GameServer.INSTANCE.couponServerApplyAddress);
            String content = response.readBodyAsString();
            return content;
        } catch (Exception ex) {
            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                    "JSON parse error in coupon apply " + code + StackTraceUtil.getStackTrace(ex)));
        }
        return null;
    }
}
